<?php
/**
 * 
 * 公共工具类
 * @author ChunYang.Jiang<chunyang@staff.sina.com.cn>
 * @copyright sina
 * @date 2011-04-09
 *
 */
class Util
{
	/**
	 * 
	 * 没有什么用，防止当前类被实例化
	 */
	private function __construct(){}
		/**
	 * 表单接收参数过滤,不支持HTML参数过滤
	 * @param unknown_type $varName 接收参数的KEY名
	 * @param unknown_type $strlen  接收参数的长度限制，0为不受限制
	 * @param unknown_type $med   参数的提交类型 支持参数post，get
	 * @param unknown_type $type  参数类型，支持str,int
	 * @param unknown_type $isSql  是否进行mysql字符串转义
	 * @param unknown_type $isClearSpace  是否清除字符里的所有空格，防止sql注入,字符串不允许有空格时才用
	 */
	public static function varFilter ($varName, $med = "post", $type = "str", $minLen=1, $maxLen=200) 
	{
		$val = '';
		if ($med == "post") {
			$val = isset($_POST[$varName]) ? $_POST[$varName] : '';
		}
		else {
			$val = isset($_GET[$varName]) ? $_GET[$varName] : '';
		}
		$val = trim($val);
		$strLen = strlen($val);
		if ($type=='str'){
			if ($strLen<$minLen || $strLen>$maxLen){
				return FALSE;
			}
			if (!preg_match('/^\w$/', $val)){
				return FALSE;
			}
		}
	}
	
	/**
	 * 返回编辑器
	 */
	public static function getFck($instance, $value='', $height=500, $width='100%', $toolbar='Default')
	{
		require_once ROOT_DIR . 'Ria/fckeditor/fckeditor.php';
		$fck = new FCKeditor($instance);
		$fck->BasePath = APP_HOST . 'Ria/fckeditor/';
		$fck->Width = $width;
		$fck->Height = $height;
		$fck->ToolbarSet = $toolbar;
		$fck->Value = $value;
		
		return $fck->CreateHtml();
	}
	
	/**
	 * 
	 * 取得hash值
	 * @param hash $data 待hash变量
	 * @param unknown_type hash基数
	 */
	public static function hashData($data, $num)
	{
		$hash = sprintf('%u', crc32($data));
		$hash = intval($hash / $num);
		$hash = intval($hash % $num);
		$hash = dechex($hash);
		return sprintf('%02s', $hash);
	}
	
	/**
	 * 设置cookies
	 * @param string $key
	 * @param unknow $value
	 */
	public static function setCookies($key, $value)
	{
		setcookie($key, $value, time() + COOKIE_EXPIRE, '/');
	}
	
	/**
	 * 返回cookies
	 * @param string $key
	 */
	public static function getCookies($key)
	{
		if (isset($_COOKIE[$key])){
			return $_COOKIE[$key];
		}
		return false;
	}
	
	/**
	 * 清空cookies
	 * @param string $key
	 */
	public static function clearCookies($key)
	{
		setcookie($key, '', time()-1, '/');
		return true;
	}
	
	/**
	 * 页面跳转
	 * @param 目标 $url
	 */
	public static function redirect($url = 'http://weibo.com') {
		@header ( "HTTP/1.1 302 Moved Temporarily" );
		@header ( "Status: 302 Moved Temporarily" );
		@header ( "Location: " . $url );
		exit ();
	}
	
	/**
	 * 操作提示
	 * @param 提示消息 $msg
	 * @param 跳转URL
	 * @param 等待时间
	 */
	public static function msgRedirect($msg, $url='-1', $time=3)
	{
		if ($url=='-1'){
			$url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '-1';
		}
		View::assign('msg', $msg);
		View::assign('jumpUrl', $url);
		View::assign('time', $time);
		View::display('system/msgRedirect.tpl.php');
		exit();
	}
	
	/**
	 * 
	 * AJAX提醒返回
	 * @param 状态码 $status
	 * @param 返回值 $msg
	 */
	public static function ajaxReturn($status, $msg=array())
	{
		$return['status'] = $status;
		$return['msg'] = $msg;
		echo json_encode($return);
		exit();
	}
	
	/**
	 * 
	 * 数据格式验证
	 * @param str $value 待验证的值
	 * @param str $rule 验证规则
	 */
	public static function regex($value,$rule) {
        $validate = array(
            'require'=> '/.+/',
            'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
            'url' => '/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/',
            'currency' => '/^\d+(\.\d+)?$/',
            'number' => '/^\d+$/',
            'zip' => '/^[1-9]\d{5}$/',
            'integer' => '/^[-\+]?\d+$/',
            'double' => '/^[-\+]?\d+(\.\d+)?$/',
            'english' => '/^[A-Za-z]+$/',
        	'time'		=>	'/[0-9]{4}-[0-9]{2}-[0-9]{2}(\s[0-9]{2}\:[0-9]{2}\:[0-9]{2})?/',
        );
        if ($rule=='date'){
        	return (bool)strtotime($value);
        }
        // 检查是否有内置的正则表达式
        if(isset($validate[strtolower($rule)]))
            $rule   =   $validate[strtolower($rule)];
        return preg_match($rule,$value)===1;
    }
	
	/**
	 * 错误日志sae_debug
	 * @param $log 错误消息
	 */
	public static function log($log)
	{
		sae_debug($log);
		return;
	}
	
	/**
	 * 生成一个随机密钥
	 */
	public static function hashCode()
	{
		return md5(Config::$EN_SECRET . microtime() . rand(0, 9999));
	}
	
	/**
	 * 生成分页代码
	 * @param $total 总记录数
	 * @param $pageSize 每页记录数
	 * @param $tpl tpl句柄
	 */
	public static function page($total, $pageSize, $tpl=null)
	{
		$page = isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page']>0
				? intval($_GET['page'])
				: 1;
		unset($_GET['page']);
		unset($_GET['router_path']);
		global $router;
		$url = '/'. $router . '?';
		foreach ($_GET as $name=>$value){
			if ($name=='page') continue;
			$url .= "$name=$value&";
		}
		
		$pageTotal = ceil($total/$pageSize);
		
		$prePage = $page>1 ? ($page-1) : 1;
		$nextPage = $page<$pageTotal ? ($page+1) : $pageTotal;
		
		$pageBreak = "<span>共{$total}条，每页{$pageSize}条，第{$page}/{$pageTotal}页</span>&nbsp;&nbsp;";
		if ($total<$pageSize){
			;
		}else{
			$pageBreak .= "<ul>";
			$pageBreak .= $page>1 ? "<li><a href='{$url}page=1'><<</a></li>" : '';
			$pageBreak .= $page>1 ? "<li><a href='{$url}page={$prePage}'><</a></li> " : '';
			for ($i=1; $i<=$pageTotal; $i++){
				$pageBreak .= $i==$page ? "<li><a href='{$url}page={$i}' style='font-weight:bold;color:#F00'>{$i}</a></li> " : "<li><a href='{$url}page={$i}'>{$i}</a></li> ";
			}
			$pageBreak .= $page<$pageTotal ? "<li><a href='{$url}page=$nextPage'>></a></li>" : '';
			$pageBreak .= $page<$pageTotal ? "<li><a href='{$url}page=$pageTotal'>>></a></li>" : '';
			$pageBreak .= "</ul>";
		}		
		return $pageBreak;
	}
	
	/*
	 * 根据IP返回真实用户信息
	 */
	public static function getIpInfo($ip)
	{
		if (is_numeric($ip)){
			$ip = long2ip($ip);
		}
		$i = 0;
		$fetchUrl = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip={$ip}&charset=utf-8&type=0&format=json";
		//重复执行两次取值的代码
		while (true){
			$i++;
			$data = @file_get_contents($fetchUrl);
			if ($data || $i>2) break;
		}
		if ($data){
			return json_decode($data, true);
		}else{
			self::log('GET IP ADDRESS ERROR,Remote Server Cannot Connect');
		}
		return false;
	}
	
	/*
	 * 获取用户IP
	 */
	public static function getIp()
	{
		if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]) && preg_match_all('/(\d{1,3}\.){3}\d{1,3}/s', $_SERVER['HTTP_X_FORWARDED_FOR'], $mat)) {
            foreach ( $mat[0] as $ip ) {
                //得到第一个非内网的IP地址
                if (!preg_match("/^(?:10|172\.16|192\.168)\./", $ip)) {
                    return $ip;
                }
            }
            return $ip;
        }
        elseif (isset($_SERVER["HTTP_X_REAL_IP"]) && preg_match_all('/(\d{1,3}\.){3}\d{1,3}/s', $_SERVER['HTTP_X_REAL_IP'], $mat)) {
            foreach ( $mat[0] as $ip ) {
                //得到第一个非内网的IP地址
                if (!preg_match("/^(?:10|172\.16|192\.168)\./", $ip)) {
                    return $ip;
                }
            }
            return $ip;
        }
        elseif (isset($_SERVER["HTTP_FROM"]) && preg_match('/(?:\d{1,3}\.){3}\d{1,3}/', $_SERVER["HTTP_FROM"])) {
            return $_SERVER["HTTP_FROM"];
        }
        else
            return $_SERVER['REMOTE_ADDR'];
	}
}